package com.yonyou.ucf.mdf.app.isvdxq.firstpart.appconfig.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.yonyou.ucf.mdf.app.isvdxq.ReturnResult.DataResult;
import com.yonyou.ucf.mdf.app.isvdxq.common.DxqConfig;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.appconfig.entity.AppconfigEntity;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.appconfig.service.AppconfigService;
import com.yonyou.ucf.mdf.app.isvdxq.other.entity.SuiteauthEntity;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.BaseService;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.MyTokenService;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.SuiteauthService;
import com.yonyou.ucf.mdf.app.isvdxq.utils.MyTool;
import com.yonyou.ucf.mdf.app.isvdxq.utils.RequestTool;
import lombok.SneakyThrows;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping(value = {DxqConfig.pre_apiUrl+"/appconfig",DxqConfig.pre_pcUrl+"/appconfig"})
public class AppconfigController {
    private static final Logger logger = LoggerFactory.getLogger(AppconfigController.class);

    @Autowired
    AppconfigService appconfigService;
    @Autowired
    BaseService baseService;
    @Autowired
    MyTokenService myTokenService;

    @Autowired
    SuiteauthService suiteauthService;



    /**
     * 更新本地应用状态
     *
     * @param appId
     * @param appKey
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/UpdateAppconfig")
    public DataResult UpdateAppconfig(String appId, String appKey, HttpServletRequest request) throws IOException {
        DataResult dataResult = new DataResult();
        //接收参数
        String tenantId = baseService.getTenantId(request);
        //参数验证
        String _appKey = DigestUtils.md5Hex(appId.replaceAll("#", tenantId));
        if (!appKey.equals(_appKey)) return dataResult;

        Map<String, Object> reqParams = RequestTool.getParams(request);
        int status = (Integer) reqParams.get("status");
        String id = (String) reqParams.get("id");
        String modifier = (String) reqParams.get("modifier");
        String modifiername = (String) reqParams.get("modifiername");
        //实体接收
        String dataListStr = (String) reqParams.get("data");
        if (!StringUtils.isEmpty(dataListStr)) {
            AppconfigEntity temp = RequestTool.getBean(dataListStr, new TypeReference<AppconfigEntity>() {
            });
            if (temp.getId() > 0) {
                id = temp.getId().toString();
                status = temp.getStatus();
            }
            if (!StringUtils.isEmpty(temp.getModifier())) {
                modifier = temp.getModifier();
                modifiername = temp.getModifiername();
            }
        }
        AppconfigEntity entity = appconfigService.SelectById(id);
        if (entity == null || entity.getId() == 0) return dataResult;
        entity.setStatus(status);
        entity.setModifyTime(MyTool.GenerateTime());
        entity.setCreator(modifier);
        entity.setModifiername(modifiername);
        int rInt = appconfigService.InsertEntity(entity);
        if (rInt == 0) return dataResult;

        dataResult.setStatus(1);
        dataResult.setMessage("操作成功");
        return dataResult;
    }

    /**
     * 添加本地应用
     *
     * @param appId
     * @param appKey
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/AddAppconfig")
    public DataResult AddAppconfig(String appId, String appKey, HttpServletRequest request) throws IOException {
        DataResult dataResult = new DataResult();
        //接收参数
        String tenantId = baseService.getTenantId(request);
        //参数验证
        String _appKey = DigestUtils.md5Hex(appId.replaceAll("#", tenantId));
        if (!appKey.equals(_appKey)) return dataResult;

        Map<String, Object> reqParams = RequestTool.getParams(request);
        String dataListStr = (String) reqParams.get("data");
        if (StringUtils.isEmpty(dataListStr)) return dataResult;

        AppconfigEntity entity = RequestTool.getBean(dataListStr, new TypeReference<AppconfigEntity>() {
        });
        entity.setId(Long.parseLong(MyTool.getRandomId()));
        entity.setCreateTime(MyTool.GenerateTime());
        entity.setVersion(2);

        int rInt = appconfigService.InsertEntity(entity);
        if (rInt == 0) return dataResult;

        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("id", entity.getId());
        dataResult.setStatus(1);
        dataResult.setMessage("操作成功");
        dataResult.setData(map);

        return dataResult;
    }

    @RequestMapping("/GetPrintConfig")
    public DataResult GetPrintConfig(HttpServletRequest request) {
        DataResult dataResult = new DataResult();
        String tenantId = baseService.getTenantId(request);
        AppconfigEntity appconfig = appconfigService.SelectLastPrintConfig(tenantId);
        if (appconfig != null) {
            dataResult.setStatus(1);
            dataResult.setMessage("操作成功");
            dataResult.setData(appconfig);
            return dataResult;
        }
        return dataResult;
    }

    /**
     * 查询应用配置
     * @param request
     * @param appcode
     * @param appType
     * @return
     */
    @RequestMapping("/GetAppConfigByCode")
    public DataResult GetAppConfigByCode(HttpServletRequest request,String appcode,Integer appType) {
        DataResult dataResult = new DataResult();
        String tenantId = baseService.getTenantId(request);
        if (StringUtils.isEmpty(appcode) || StringUtils.isEmpty(tenantId) || appType == null) {
            return dataResult;
        }
        AppconfigEntity appconfigEntity = appconfigService.SelectByAppcode(appcode, appType, tenantId);
        dataResult.setData(appconfigEntity);
        return dataResult;
    }


    /**
     * 在线查询数据库表名
     * /apidxq/isv2/appconfig/GetTabinfoList?tenant_id=&access_token=&dbName=
     *
     * @param request
     * @return
     */
    @RequestMapping("/GetTabinfoList")
    public DataResult GetTabinfoList(HttpServletRequest request) {
        DataResult result = new DataResult(1, "查询成功");
        String tenantId = baseService.getTenantId(request);
        try {
            Map<String, Object> reqParams = RequestTool.getParams(request);
            String dbName = (String) reqParams.get("dbName");
            if (!StringUtils.isEmpty(dbName)) {
                List<?> list = appconfigService.SelectTabInfoById(dbName);
                result.setDataList(list);
                result.setTotalSizeEx(list.size());
            }
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    /**
     * 修改指定租户 失效时间
     *
     * @param rt      失效时间 秒 当前默认值1800
     * @param request
     * @return
     * @throws Exception
     */
    @SneakyThrows
    @RequestMapping("/SetTokenRefreshTime")
    public DataResult SetTokenRefreshTime(Integer rt, HttpServletRequest request) throws Exception {
        DataResult result = new DataResult(1, "操作成功");
        try {
            String tenantId = baseService.getTenantId(request);
            List<SuiteauthEntity> suiteauthEntities = new ArrayList<>();
            if (!StringUtils.isEmpty(tenantId)) {
                suiteauthEntities = suiteauthService.SelectByTenantId(tenantId);
            } else {
                suiteauthEntities = suiteauthService.SelectAll();
            }
            result.setDataList(suiteauthEntities);
            if (rt != null) {
                suiteauthService.EditrefreshTime(rt, tenantId);
            }
        } catch (Exception ex) {
            result = new DataResult(0, "操作失败");
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    



}
